import {
  LogsController,
  MetaStorage,
  getAppEnvConfig,
  isFunction,
} from "@/utils";
import { CACHE_CONFIG } from "@/config";
import type { App } from "vue";

export function initProjectLogics(app: Nullable<App<Element>>) {
  //存储初始化
  MetaStorage.start(CACHE_CONFIG);

  //初始化钩子
  initHooks();

  //注册全局组件
  useAppCommon(app);

  //开启错误日志
  initErrorLogs();
}

function initHooks() {
  //初始化themeHooks
}

function useAppCommon(app: Nullable<App<Element>>) {
  const modules = import.meta.glob("../common/**/index.tsx", { eager: true });
  for (let module of Object.values(modules)) {
    let val = (module as any).default;
    if (val.name) {
      app?.component(val.name, val);
    }
  }
}

function initErrorLogs() {
  let { logs } = getAppEnvConfig();

  if (logs === "true") {
    //代理console
    console = new Proxy(console as Console & { [key: string]: any }, {
      get(target, property) {
        let handle = target[property as string];
        if (isFunction(handle)) {
          return function (...args: any[]) {
            if (property === "error") {
              LogsController.factory().writeLogs(args.join("") as string);
            }
            handle.apply(target, args);
          };
        }
        return handle;
      },
    });

    //监听window.error

    window.addEventListener("error", ({ error ,message  }) => {
      let { stack } = error || {};  
      let errorText = stack ?? message
      if(errorText){
        LogsController.factory().writeLogs(errorText);
      }
      
    });
  }
}
